/**
 * HTML代码详情页面
 * 显示HTML代码的详细信息，包括代码展示和预览功能
 * 使用项目统一的UI组件保持界面一致性
 */

import React, { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useHtmlCode } from '../../lib/api/hooks/use-api.js';
import { Container } from '@/components/common/container';
import { Toolbar, ToolbarActions, ToolbarHeading } from '@/layouts/demo1/components/toolbar';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Label } from '@/components/ui/label';
import { ArrowLeft, Edit, Copy, Download, Eye, Code, FileText, Calendar, User, Hash } from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism';
import HtmlPreview from '@/components/html-preview/html-preview';

/**
 * HTML代码详情页面组件
 * 展示HTML代码的完整信息，包括基本信息和代码内容
 */
const HtmlCodeDetailPage = () => {
  // 路由相关
  const navigate = useNavigate();
  const { id } = useParams(); // 获取URL参数中的ID
  const [activeTab, setActiveTab] = useState('info'); // 当前激活的标签页

  // 获取HTML代码详情数据
  const { 
    data: htmlCodeData, 
    isLoading, 
    error, 
    refetch 
  } = useHtmlCode(id);

  // 处理返回列表
  const handleBack = () => {
    navigate('/html-code-management');
  };

  // 处理编辑
  const handleEdit = () => {
    navigate(`/html-code-management/edit/${id}`);
  };

  // 处理复制代码
  const handleCopyCode = async () => {
    if (htmlCodeData?.page) {
      try {
        await navigator.clipboard.writeText(htmlCodeData.page);
        alert('代码已复制到剪贴板');
      } catch (error) {
        console.error('复制失败:', error);
        alert('复制失败，请手动复制');
      }
    }
  };

  // 处理下载代码
  const handleDownloadCode = () => {
    if (htmlCodeData?.page) {
      const blob = new Blob([htmlCodeData.page], { type: 'text/html' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${htmlCodeData.name || 'html-code'}.html`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '未知';
    return new Date(dateString).toLocaleString('zh-CN');
  };

  // 获取状态徽章
  const getStatusBadge = (status) => {
    switch (status) {
      case 'active':
        return <Badge variant="success" size="sm">活跃</Badge>;
      case 'inactive':
        return <Badge variant="secondary" size="sm">非活跃</Badge>;
      case 'draft':
        return <Badge variant="warning" size="sm">草稿</Badge>;
      default:
        return <Badge variant="outline" size="sm">{status || '未知'}</Badge>;
    }
  };

  // 渲染基本信息
  const renderBasicInfo = () => (
    <div className="space-y-6">
      {/* 基本信息卡片 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="size-5" />
            基本信息
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">页面名称</Label>
              <div className="flex items-center gap-2">
                <span className="font-medium">{htmlCodeData.name || '未命名'}</span>
                {getStatusBadge(htmlCodeData.status)}
              </div>
            </div>
            
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">工作空间ID</Label>
              <div className="flex items-center gap-2">
                <Hash className="size-4 text-muted-foreground" />
                <span>{htmlCodeData.workspace_id || '未设置'}</span>
              </div>
            </div>
            
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">页面ID</Label>
              <div className="flex items-center gap-2">
                <Hash className="size-4 text-muted-foreground" />
                <span>{htmlCodeData.page_id || '未设置'}</span>
              </div>
            </div>
            
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">应用程序ID</Label>
              <div className="flex items-center gap-2">
                <Hash className="size-4 text-muted-foreground" />
                <span>{htmlCodeData.app_id || '未设置'}</span>
              </div>
            </div>
          </div>
          
          {htmlCodeData.content && (
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">内容描述</Label>
              <p className="text-sm leading-relaxed">{htmlCodeData.content}</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 统计信息卡片 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Code className="size-5" />
            代码统计
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">
                {htmlCodeData.page?.length || 0}
              </div>
              <div className="text-sm text-muted-foreground">字符数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">
                {htmlCodeData.page?.split('\n').length || 0}
              </div>
              <div className="text-sm text-muted-foreground">行数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">
                {htmlCodeData.page?.split(' ').filter(word => word.trim()).length || 0}
              </div>
              <div className="text-sm text-muted-foreground">单词数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">
                {htmlCodeData.page ? Math.round(htmlCodeData.page.length / 1024 * 100) / 100 : 0}
              </div>
              <div className="text-sm text-muted-foreground">KB</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 元数据信息 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="size-5" />
            元数据信息
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">创建时间</Label>
              <div className="flex items-center gap-2">
                <Calendar className="size-4 text-muted-foreground" />
                <span className="text-sm">{formatDate(htmlCodeData.created_at)}</span>
              </div>
            </div>
            
            <div className="space-y-2">
              <Label className="text-sm font-medium text-muted-foreground">更新时间</Label>
              <div className="flex items-center gap-2">
                <Calendar className="size-4 text-muted-foreground" />
                <span className="text-sm">{formatDate(htmlCodeData.updated_at)}</span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );

  // 渲染HTML代码
  const renderHtmlCode = () => (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <Code className="size-5" />
            HTML源代码
          </CardTitle>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={handleCopyCode}
              disabled={!htmlCodeData?.page}
            >
              <Copy className="size-4 me-2" />
              复制代码
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleDownloadCode}
              disabled={!htmlCodeData?.page}
            >
              <Download className="size-4 me-2" />
              下载
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {htmlCodeData?.page ? (
          <div className="border rounded-lg overflow-hidden">
            <SyntaxHighlighter
              language="html"
              style={tomorrow}
              showLineNumbers
              wrapLines
              wrapLongLines
              className="!m-0 !rounded-none"
            >
              {htmlCodeData.page}
            </SyntaxHighlighter>
          </div>
        ) : (
          <div className="text-center py-8 text-muted-foreground">
            <Code className="size-12 mx-auto mb-4 opacity-50" />
            <p>该记录没有HTML代码内容</p>
          </div>
        )}
      </CardContent>
    </Card>
  );

  // 渲染HTML预览
  const renderHtmlPreview = () => (
    <HtmlPreview
      htmlContent={htmlCodeData?.page}
      title="HTML预览"
      showStats={true}
      showControls={true}
    />
  );

  // 加载状态
  if (isLoading) {
    return (
      <Container>
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
          <p className="mt-2 text-muted-foreground">加载中...</p>
        </div>
      </Container>
    );
  }

  // 错误状态
  if (error) {
    return (
      <Container>
        <div className="text-center py-8">
          <div className="text-destructive mb-4">
            <FileText className="size-12 mx-auto mb-2" />
            <p>加载失败: {error.message}</p>
          </div>
          <div className="flex items-center justify-center gap-4">
            <Button variant="outline" onClick={handleBack}>
              返回列表
            </Button>
            <Button onClick={() => refetch()}>
              重试
            </Button>
          </div>
        </div>
      </Container>
    );
  }

  // 数据不存在
  if (!htmlCodeData) {
    return (
      <Container>
        <div className="text-center py-8">
          <div className="text-muted-foreground mb-4">
            <FileText className="size-12 mx-auto mb-2" />
            <p>HTML代码不存在</p>
          </div>
          <Button variant="outline" onClick={handleBack}>
            返回列表
          </Button>
        </div>
      </Container>
    );
  }

  return (
    <>
      {/* 页面标题和操作栏 */}
      <Container>
        <Toolbar>
          <ToolbarHeading
            title={htmlCodeData.name || 'HTML代码详情'}
            description="查看页面对象的详细信息和内容"
          />
          <ToolbarActions>
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="size-4 me-2" />
              返回列表
            </Button>
            <Button onClick={handleEdit}>
              <Edit className="size-4 me-2" />
              编辑
            </Button>
          </ToolbarActions>
        </Toolbar>
      </Container>

      {/* 详情内容 */}
      <Container>
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="info" className="flex items-center gap-2">
              <FileText className="size-4" />
              基本信息
            </TabsTrigger>
            <TabsTrigger value="code" className="flex items-center gap-2">
              <Code className="size-4" />
              源代码
            </TabsTrigger>
            <TabsTrigger value="preview" className="flex items-center gap-2">
              <Eye className="size-4" />
              预览
            </TabsTrigger>
          </TabsList>

          {/* 基本信息标签页 */}
          <TabsContent value="info" className="space-y-6">
            {renderBasicInfo()}
          </TabsContent>

          {/* 源代码标签页 */}
          <TabsContent value="code" className="space-y-6">
            {renderHtmlCode()}
          </TabsContent>

          {/* 预览标签页 */}
          <TabsContent value="preview" className="space-y-6">
            {renderHtmlPreview()}
          </TabsContent>
        </Tabs>
      </Container>
    </>
  );
};

export default HtmlCodeDetailPage;